# coding:utf-8
import re
import json
import requests
from config import ctfdata
from config import usernames


def ctfoneuser(username):
    session = requests.Session()  # 构造Session
    for k in range(10):
        try:
            resp = session.post('http://vsew.jmu.edu.cn/auth/login',
                                {"email": str(username), "password": str(username), "next": "/course"})  # 登录
        except requests.exceptions.ConnectionError as e:
            print("Error:" + str(e) + str(k) + "/10, try again")
            continue
        try:
            print(str(username) + " login " + resp.json()['message'])
            if resp.json()['message'] == "账号或密码错误":
                return resp.json()['message']
            break
        except json.JSONDecodeError as e:
            print("Error:" + str(e) + str(k) + "/10, try again")

    ids = []
    for i in range(1, 13):  # 获取未完成题目id
        resp = session.get('http://vsew.jmu.edu.cn/ctf/list?page=' + str(i) + '&page_size=21&subject_id=&type=&degree=&pass=0')
        list_data = resp.json()['data']['list']['data']
        if len(list_data) == 0:
            break
        for li in list_data:
            ids.append(li['id'])

    total = len(ids)
    count = 0

    for id in ids:
        id = str(id)
        count += 1
        print(str(count) + "/" + str(total) + " - GET "+id+" "),
        resp = session.get('http://vsew.jmu.edu.cn/ctf/' + id + '/')
        try:
            print(re.findall("<title.*?\/title>", resp.text)[0][7:-16])
        except:
            print(re.findall("<title.*?\/title>", resp.text))

        print(" open VM:"),
        while True:
            try:
                resp = session.post('http://vsew.jmu.edu.cn/ctf/' + id + '/start')
                print(resp.json()["message"])
                break
            except:
                print('fail, try again!')

        flag = ctfdata.get(id)
        if flag == None:
            print("don't save this question answer!")
            continue
        print(" submit Flag:"),
        resp = session.post('http://vsew.jmu.edu.cn/ctf/' + id + '/flag', {"flag": flag, "record_id": "50612", "type": "0"})
        print(resp.json()["message"])


if __name__ == '__main__':
    for username in usernames:
        ctfoneuser(username)